import 'dart:async';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/location_gps.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

/// 定位工具类
abstract class LocationUtil {

  /// 是否持续获取位置信息
  static bool shouldGetLocation = true;

  /// 获取当前位置
  static Future<Position> getCurrentLocation() async {
    try {
      await openLocationSettings();
      final Position position = await Geolocator.getCurrentPosition();
      AppLogger.log('当前位置：${position.latitude}，${position.longitude}-高度:${position.altitude}');
      return position;
    } catch (e) {
      AppLogger.log('获取当前位置失败：$e');
      return Future.error(e);
    }
  }

  /// 请求权限
  static Future<bool> openLocationSettings() async {
    // 检查是否已经授予位置权限
    var status = await Permission.location.status;
    // 是否已经授予一直获取位置权限
    var alwaysStatus = await Permission.locationAlways.status;
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      // 如果权限被拒绝，请求权限
      status = await Permission.location.request();
    } else if (alwaysStatus.isDenied) {
      // 如果权限被拒绝，请求权限
      status = await Permission.locationAlways.request();
    }
    // 根据请求权限后的状态处理
    if (status.isGranted ) {
      // 权限被授予
      return true;
    } else {
      // 权限被拒绝
      AppLogger.log('位置权限被拒绝');
      return false;
    }
  }

  /// 经纬度信息list
  static List positions = [];



  static StreamSubscription<Map<String, Object>>? _locationListener;



  static Map<String, Object>? _locationResult;

  /// 持续获取位置信息
  static void listenLocation() async {
    final bool isOpen = await openLocationSettings();
    if (!isOpen) {
      AppToast.showWarning('请打开位置权限');
      return;
    }
    if(shouldGetLocation) {
      return;
    }
    shouldGetLocation = true;


    // /// 每两秒获取定位
    // while (shouldGetLocation) {
    //   try {
    //     final Position position = await Geolocator.getCurrentPosition();
    //     positions.add(position);
    //     AppLogger.log('当前位置：${position.latitude}，${position.longitude}-高度：${position.altitude}');
    //     // // 上传位置信息
    //     await HttpUtil().generatePostRequest(Interface.addLocation, data: {
    //       'altitude': position.altitude,
    //       'companyCode': UserManager.getUser()?.systemUser?.companyCode,
    //       'createBy': '',
    //       'createDate': '',
    //       'deleted': '',
    //       'id': '',
    //       'latitude': position.latitude,
    //       'locationTime': '',
    //       'longitude': position.longitude,
    //       'updateBy': '',
    //       'updateDate': '',
    //       'userId': UserManager.getUserId(),
    //       'userName': UserManager.getUser()?.systemUser?.nickname
    //     }).execute(isShowToast: false);
    //     await Future.delayed(const Duration(milliseconds: 2000));
    //   } catch (e) {
    //     AppLogger.log('获取位置信息失败：$e');
    //     shouldGetLocation = false;
    //   }
    // }

    // 高德地图
    final AMapFlutterLocation _locationPlugin =  AMapFlutterLocation();
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey('6c3ba8cc43b002518adf5255ed2c9700', 'ios ApiKey');
    //设置当前GPS定位
    ///注册定位结果监听
    _locationListener = _locationPlugin.onLocationChanged().listen((Map<String, Object> result) {
      _locationResult = result;
      positions.add(result);
      List res = GpsUtil.gcj02_To_Gps84(result['latitude'] as num, result['longitude'] as num);
      // AppLogger.log('当前高德位置：${result['longitude']},${result['latitude']}-高度：${result['altitude']}');
      AppLogger.log('当前gps位置：${res[1]},${res[0]}-高度：${result['altitude']}');
      upLoad(result,res);
    });
    _locationPlugin.setLocationOption(AMapLocationOption(
      locationMode: AMapLocationMode.Hight_Accuracy,
      needAddress: false,
    ));

    _locationPlugin.startLocation();


  }


  // 上传数据
  static upLoad(Map<String, Object> result,List<dynamic> res) async {
    if(UserManager.isLoggedIn) {
      await HttpUtil().generatePostRequest(Interface.addLocation, data: {
        'altitude': result['altitude'],
        'companyCode': UserManager.getUser()?.systemUser?.companyCode,
        'createBy': '',
        'createDate': '',
        'deleted': '',
        'id': '',
        'latitude': res[0],
        'locationTime': '',
        'longitude': res[1],
        'updateBy': '',
        'updateDate': '',
        'userId': UserManager.getUserId(),
        'userName': UserManager.getUser()?.systemUser?.nickname
      }).execute(isShowToast: false,isPrinting:false);
    }
  }


  /// 关闭持续获取位置信息
  static void cancelListenLocation() {
    shouldGetLocation = false;
  }

  /// 监听位置服务状态
  static void listenServiceStatus() {
    Geolocator.getServiceStatusStream().listen((event) {
      AppToast.showWarning('位置服务${event.name}');
    });
  }

  // 百度定位
  _baidu() {
    // 百度定位
    /// 设置是否隐私政策
    /// 隐私政策官网链接：https://lbsyun.baidu.com/index.php?title=openprivacy
    /// 通知用户之后根据用户选择进行赋值
    // var b = await myLocPlugin.setAgreePrivacy(true);
    //
    // myLocPlugin.getApiKeyCallback(callback: (String result) {
    //   String str = result;
    //   print('鉴权结果：' + str);
    // });
    //
    // myLocPlugin.seriesLocationCallback(callback: (BaiduLocation position) {
    //   // positions.add(position);
    //   AppLogger.log('-当前位置：${position.latitude}，${position.longitude}-高度：${position.altitude}');
    //   // // 上传位置信息
    //   HttpUtil().generatePostRequest(Interface.addLocation, data: {
    //     'altitude': position.altitude,
    //     'companyCode': UserManager.getUser()?.systemUser?.companyCode,
    //     'createBy': '',
    //     'createDate': '',
    //     'deleted': '',
    //     'id': '',
    //     'latitude': position.latitude,
    //     'locationTime': '',
    //     'longitude': position.longitude,
    //     'updateBy': '',
    //     'updateDate': '',
    //     'userId': UserManager.getUserId(),
    //     'userName': UserManager.getUser()?.systemUser?.nickname
    //   }).execute();
    // });
    //
    // final Map androidMap = initAndroidOptions().getMap();
    //
    // final fuck = await myLocPlugin.prepareLoc(androidMap, androidMap);
    //
    // /// 设置是否隐私政策
    // /// 隐私政策官网链接：https://lbsyun.baidu.com/index.php?title=openprivacy
    // /// 通知用户之后根据用户选择进行赋值
    // await myLocPlugin.setAgreePrivacy(true);
    //
    // final start = await myLocPlugin.startLocation();
    //
    // if(start) {
    //   AppToast.showSuccess('定位启动成功',duration: const Duration(seconds: 2));
    // } else {
    //   AppToast.showError('定位启动失败',duration: const Duration(seconds: 2));
    // }

  }

}
